<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class StoreGroup extends Model
{
    use SoftDeletes;

    protected $table = 'ims_yz_store_groups';

    protected $fillable = [
        'group_name',
        'province_id',
        'city_id',
        'district_id',
        'type_id',
        'created_at',
        'updated_at',
        'deleted_at',
    ];

    protected $casts = [
        'id' => 'integer',
        'province_id' => 'integer',
        'city_id' => 'integer',
        'district_id' => 'integer',
        'type_id' => 'integer',
        'created_at' => 'integer',
        'updated_at' => 'integer',
        'deleted_at' => 'integer',
    ];

    /**
     * 软删除字段名
     */
    const DELETED_AT = 'deleted_at';

    /**
     * 关联门店群组关联表
     */
    public function storeGroupStores()
    {
        return $this->hasMany(StoreGroupStore::class, 'group_id', 'id');
    }

    /**
     * 关联门店（通过关联表）
     */
    public function stores()
    {
        return $this->belongsToMany(Store::class, 'ims_yz_store_group_stores', 'group_id', 'store_id');
    }

    /**
     * 根据省市区查询群组
     */
    public function scopeByLocation($query, $provinceId, $cityId, $districtId)
    {
        return $query->where('province_id', $provinceId)
                    ->where('city_id', $cityId)
                    ->where('district_id', $districtId);
    }

    /**
     * 根据分类查询群组
     */
    public function scopeByType($query, $typeId)
    {
        return $query->where('type_id', $typeId);
    }

    /**
     * 获取群组名称
     */
    public function getGroupNameAttribute($value)
    {
        return $value;
    }

    /**
     * 设置群组名称
     */
    public function setGroupNameAttribute($value)
    {
        $this->attributes['group_name'] = $value;
    }
}
